//
//  UserInfoChangeViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/22.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "UserInfoChangeViewController.h"
#import "ChangeNickNameViewController.h"

#import "LYLPhotoTailoringTool.h"

#import "UserInfoChangeCell.h"

#import <AFHTTPSessionManager.h>

@interface UserInfoChangeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation UserInfoChangeViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = kLocalizedString(@"基本资料修改", nil);

    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
}

#pragma mark - ChangeLanguageNotification

- (void)changeLanguage
{
    self.navigationItem.title = kLocalizedString(@"基本资料修改", nil);
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserInfoChangeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.indexRow = indexPath.row;
    cell.userInfoDic = self.dataArray[indexPath.row];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        @weak(self)
        [[LYLPhotoTailoringTool sharedTool]photoTailoringIsRoundImage:YES finish:^(UIImage *image) {
            
            image = [UIImage fixOrientation:image];
            [self_weak_ startClearBgColorLoading];
           
            NSDictionary *parameters = @{@"userId":[CBTLocalUserManager sharedInstance].userId};
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.requestSerializer.timeoutInterval = 30;
            
            if ([HEFANTV_DEVICETOKEN length] > 0)
            {
                [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@_%@",[CBTLocalUserManager sharedInstance].userId,HEFANTV_DEVICETOKEN] forHTTPHeaderField:@"authorization"];
            }
            //在请求头中添加当前语言
            [manager.requestSerializer setValue:[kLanguageManager isSimplified] ? @"language_zh" : @"language_en" forHTTPHeaderField:@"language"];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
            
            [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL_STATIC,@"/cbt/setPicUrl"] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                
                UIImage *imagead  = image;
                NSData *imageData = UIImageJPEGRepresentation(imagead, 0.5);
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                // 设置时间格式
                [formatter setDateFormat:@"yyyyMMddHHmmss"];
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
                [formData appendPartWithFileData:imageData name:@"picture" fileName:fileName mimeType:@"image/jpeg"];
                
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                //上传进度
                dispatch_sync(dispatch_get_main_queue(), ^{
                    NSLog(@"progress is %@",uploadProgress);
                });
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [self_weak_ stopLoading];
                
                [HFStatusView showSuccessMessage:kLocalizedString([[responseObject objectForKey:@"code"]intValue] == 100 ? @"上传成功" : @"上传失败", nil)];
                
                if ([responseObject[@"code"]intValue] == 100) {
                    [CBTImageTools saveUserImageWithImage:image imageName:[responseObject[@"data"]objectForKey:@"picUrl"] userID:[responseObject[@"data"]objectForKey:@"userId"]];
                    
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserInfo" object:nil userInfo:@{@"type":@"image",@"image":image}];
                    
                    [[CBTLocalUserManager sharedInstance]refreshUserInfoDic:@{@"picUrl":[NSString stringWithFormat:@"%@",[responseObject[@"data"]objectForKey:@"picUrl"]]}];
                    
                    [((UserInfoChangeCell *)[self_weak_.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]])changeImageViewImage:image];
                }
            
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self_weak_ stopLoading];
                NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)task.response;
                if (urlResponse.statusCode == 403 || urlResponse.statusCode == 401) {
                    [HFStatusView showFailureMessage:kLocalizedString(@"您的登录已失效，请重新登录!",nil)];
                    [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:HEFANTV_TOKEN];
                    [[NSUserDefaults standardUserDefaults]synchronize];
                    [[CBTLocalUserManager sharedInstance]removeUserInfo];
                    [((AppDelegate*)[UIApplication sharedApplication].delegate) changeRootVC];
                }else{
                    [HFStatusView showFailureMessage:kLocalizedString(@"上传失败", nil)];
                }
            }];
            
            
            
//            NSString *url = [NSString stringWithFormat:@"%@%@",kBaseURL_STATIC,@"/cbt/setPicUrl"];
//
//            NSDictionary *parameters = @{@"userId":[CBTLocalUserManager sharedInstance].userId};
//
//            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
//            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
//                                                                 @"text/html",
//                                                                 @"image/jpeg",
//                                                                 @"image/png",
//                                                                 @"application/octet-stream",
//                                                                 @"text/json", nil];
//
//            [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//                // 获取图片数据
//                NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
//                // 设置上传图片的名字
//                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//                formatter.dateFormat = @"yyyyMMddHHmmss";
//                NSString *str = [formatter stringFromDate:[NSDate date]];
//                NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
//                [formData appendPartWithFileData:fileData name:@"picture" fileName:fileName mimeType:@"image/png"];
//
//            } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                // 返回结果
//                NSLog(@"%@",responseObject);
//                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeUserInfo" object:nil userInfo:@{@"type":@"image",@"image":image}];
//                [((UserInfoChangeCell *)[weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]])changeImageViewImage:image];
//
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                NSLog(@"%@",error);
//            }];
            
            
            
     
        
//            NSString *url =@"http://192.168.31.141:8080/backend_cloud_commodity/cbt/setPicUrl/";
//            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//            manager.requestSerializer.timeoutInterval = 20;
//            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
//            NSDictionary *parameters = @{@"userId":[CBTLocalUserManager sharedInstance].userId};
//            [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//                // 获取图片数据
//                NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
//                // 设置上传图片的名字
//                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//                formatter.dateFormat = @"yyyyMMddHHmmss";
//                NSString *str = [formatter stringFromDate:[NSDate date]];
//                NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
//                /*
//                 *该方法的参数
//                 1. appendPartWithFileData：要上传的照片[二进制流]
//                 2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
//                 3. fileName：要保存在服务器上的文件名
//                 4. mimeType：上传的文件的类型
//                 */
//                [formData appendPartWithFileData:fileData name:@"picture" fileName:fileName mimeType:@"image/png"];
//
//            } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//                //上传进度
//                dispatch_sync(dispatch_get_main_queue(), ^{
//                    NSLog(@"progress is %@",uploadProgress);
//                });
//
//            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                NSLog(@"%@",responseObject);
//
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                NSLog(@"%@",error);
//
//            }];
        }];
    }else{
        ChangeNickNameViewController *vc = [[ChangeNickNameViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

#pragma mark - Lazy

- (NSArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = @[@{@"title":@"修改头像",@"img":@"wode_ziliao_touxiang"},
                       @{@"title":@"修改昵称",@"img":@"wode_ziliao_nicheng"}];
    }
    return _dataArray;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenNarrowSide, ScreenWideSide - self.tabBarController.tabBar.bounds.size.height - 15) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        
        _tableView.delegate   = self;
        _tableView.dataSource = self;
        
        if (@available(iOS 11.0, *)){
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight           = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        
        [_tableView registerClass:[UserInfoChangeCell class] forCellReuseIdentifier:@"Cell"];
        
        _tableView.tableFooterView = [UIView new];
    }
    
    return _tableView;
}

@end
